﻿using EmoneyWeiXinCommon;
using EmoneyWeiXinEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace EmoneyWeiXin.Controllers
{
    public class SendModelMsgController : Controller
    {
        static string url = Config.WeiXin_ApiUrl + "message/template/send?access_token={0}";
        //
        // GET: /SendModelMsg/
        /// <summary>
        /// 发送优惠券码
        /// </summary>
        /// <returns></returns>
        public ActionResult SendYhqm()
        {


            return Content("1");
            //string openid = Request["openid"];
            //string code = Request["code"];

            //if (openid == null || code == null)
            //{
            //    return Content("openid和code都不能为空");
            //}
            //string token = TokenHelper.GetToken("wx25bf1ed19bab0096", "d1067af0669ab1d98ee27adad3f98c5c");
            //bool isneedRefreshToken;
            //ModelMessagesEntity model = new ModelMessagesEntity()
            //{
            //    firstText = "恭喜您抢券成功，特价券信息如下：",
            //    keyNote1 = code,
            //    touser = openid,
            //    keyNote2 = "1111底价券",
            //    keyNote3 = "2015.11.11-11.14",
            //    remarkText = "11.11-11.14购买益盟操盘手决策加强版即享底价，详询4006021026."
            //};
            //bool isSuccess = Send(token, model, out isneedRefreshToken);
            //if (isSuccess)
            //{
            //    return Content("1");
            //}
            //else
            //{
            //    if (isneedRefreshToken)  //如果是token过期，则刷新token
            //    {
            //        TokenHelper.ClearToken();
            //        isSuccess = Send(token, model, out isneedRefreshToken);
            //        if (isSuccess)
            //        {
            //            return Content("1");
            //        }
            //        else
            //        {
            //            return Content("发送失败");
            //        }
            //    }
            //    else
            //    {
            //        return Content("发送失败");
            //    }
            //}
            // ModelMessagesModel
        }

        public static bool Send(string accessToken, ModelMessagesEntity item, out bool isneedRefreshToken)
        {
            string json = CreateYHQModelJson(item);
            string returnJson = NetHelper.LoadDataPost(string.Format(url, accessToken), null, json, Encoding.UTF8);
            if (returnJson.IndexOf("{\"errcode\":40001") != -1)
            {
                isneedRefreshToken = true;
                return false;
            }
            else
            {
                isneedRefreshToken = false;
            }
            returnJsonModel jm = JsonTools.ToObject<returnJsonModel>(returnJson);
            if (jm.errmsg == "ok") //
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 创建领券的模板消息的json
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static string CreateYHQModelJson(ModelMessagesEntity entity)
        {
            var jsonObj = new
            {
                touser = entity.touser,
                template_id = "8hnHSj6nHjmJL1GZemuXBLfUN2VES__4ocym43KrXck",
                url = entity.url,
                topcolor = "#FF0000",
                data = new
                {
                    first = new { value = entity.firstText, color = "#173177" },
                    keyword1 = new { value = entity.keyNote1, color = "#173177" },
                    keyword2 = new { value = entity.keyNote2, color = "#173177" },
                    keyword3 = new { value = entity.keyNote3, color = "#173177" },
                    remark = new { value = entity.remarkText, color = "#173177" },
                }
            };
            return JsonTools.ToJson(jsonObj);
        }

        //授权回调
        public ActionResult RedirectToLingQuan()
        {
            try
            {
                string code = Request["code"];
                string posrUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" + string.Format("?appid={0}&secret={1}&code={2}&grant_type=authorization_code", "wx25bf1ed19bab0096", "d1067af0669ab1d98ee27adad3f98c5c", code);
                string jsonResult = NetHelper.LoadData(posrUrl, null);
                JsonModelEntity jm = JsonTools.ToObject<JsonModelEntity>(jsonResult);
                string goUrl = System.Configuration.ConfigurationManager.AppSettings["lingquanUrl"];
                if (goUrl.Contains("?"))
                {
                    goUrl += "&openid=" + jm.openid;
                }
                else
                {
                    goUrl += "?openid=" + jm.openid;
                }
                Response.Redirect(goUrl);
            }
            catch (Exception)
            {

            }
            return Content("发生了错误，请重试");
        }
    }

    class returnJsonModel
    {
        public string errcode { get; set; }
        public string errmsg { get; set; }
        public string msgid { get; set; }

    }

    class JsonModelEntity
    {
        public string access_token { get; set; }
        public string expires_in { get; set; }
        public string refresh_token { get; set; }
        public string openid { get; set; }
        public string scope { get; set; }
        public string unionid { get; set; }
    }

}
    